package com.micro.ai.auth.service.impl;

import com.micro.ai.auth.service.RedisService;
import com.micro.ai.auth.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 短信服务实现
 * 
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@Service
public class SmsServiceImpl implements SmsService {

    @Autowired
    private RedisService redisService;

    @Value("${sms.expire-time:300}")
    private Integer smsExpireTime;

    @Value("${sms.rate-limit:60}")
    private Integer smsRateLimit;

    private static final String SMS_PREFIX = "sms:";
    private static final String SMS_RATE_LIMIT_PREFIX = "sms:rate:";

    @Override
    public boolean sendSmsCode(String phone, String code) {
        try {
            // 检查发送频率限制
            if (!canSendSms(phone)) {
                log.warn("短信发送频率超限: phone={}", phone);
                return false;
            }

            // TODO: 集成阿里云短信服务
            // 这里模拟发送短信
            log.info("发送短信验证码: phone={}, code={}", phone, code);
            
            // 存储验证码到Redis
            String redisKey = SMS_PREFIX + phone;
            redisService.set(redisKey, code, smsExpireTime, TimeUnit.SECONDS);
            
            // 设置发送频率限制
            String rateLimitKey = SMS_RATE_LIMIT_PREFIX + phone;
            redisService.set(rateLimitKey, "1", smsRateLimit, TimeUnit.SECONDS);
            
            log.info("短信验证码发送成功: phone={}", phone);
            return true;
            
        } catch (Exception e) {
            log.error("短信发送失败: phone={}, error={}", phone, e.getMessage());
            return false;
        }
    }

    @Override
    public boolean validateSmsCode(String phone, String code) {
        try {
            if (phone == null || code == null) {
                return false;
            }
            
            String redisKey = SMS_PREFIX + phone;
            String storedCode = redisService.get(redisKey, String.class);
            
            if (storedCode == null) {
                log.warn("短信验证码已过期或不存在: phone={}", phone);
                return false;
            }
            
            boolean isValid = storedCode.equals(code);
            
            if (isValid) {
                // 验证成功后删除验证码
                redisService.delete(redisKey);
                log.info("短信验证码验证成功: phone={}", phone);
            } else {
                log.warn("短信验证码验证失败: phone={}, input={}, stored={}", phone, code, storedCode);
            }
            
            return isValid;
            
        } catch (Exception e) {
            log.error("短信验证码验证失败: phone={}, error={}", phone, e.getMessage());
            return false;
        }
    }

    @Override
    public String generateSmsCode() {
        // 生成6位数字验证码
        Random random = new Random();
        int code = 100000 + random.nextInt(900000);
        return String.valueOf(code);
    }

    @Override
    public boolean canSendSms(String phone) {
        try {
            String rateLimitKey = SMS_RATE_LIMIT_PREFIX + phone;
            return !redisService.hasKey(rateLimitKey);
        } catch (Exception e) {
            log.error("检查短信发送频率失败: phone={}, error={}", phone, e.getMessage());
            return false;
        }
    }
}
